iT邦幫忙

0

跟著AI一起:從零打造一個互動式網站 Day22

wqq 2025-10-07 12:41:41110 瀏覽
  • 分享至 

  • xImage
  •  

實作 API 範例:顯示即時天氣資料

  1. 選擇天氣 API
    這裡用 OpenWeatherMap API(免費,常用練習 API):
    註冊後可以拿到一個 API Key。
    範例 API 連結(測試用):

https://api.openweathermap.org/data/2.5/weather?q=Taipei&appid=demo&units=metric

參數說明:

  • q=Taipei:查詢台北市
  • appid=demo:API Key(要換成自己帳號的 key)
  • units=metric:用攝氏溫度
  1. 基本 Fetch 範例
fetch("https://api.openweathermap.org/data/2.5/weather?q=Taipei&appid=demo&units=metric")
  .then(res => res.json())
  .then(data => {
    console.log(data);
    console.log("城市:", data.name);
    console.log("溫度:", data.main.temp, "°C");
    console.log("天氣:", data.weather[0].description);
  })
  .catch(err => console.error(err));
  1. 實作:輸入城市查天氣
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <title>Day22 天氣查詢</title>
</head>
<body>
  <h1>天氣查詢系統</h1>
  <input type="text" id="city" placeholder="輸入城市名稱,如 Taipei">
  <button id="btn">查詢</button>

  <div id="result"></div>

  <script>
    const btn = document.getElementById("btn");
    const result = document.getElementById("result");

    btn.addEventListener("click", () => {
      const city = document.getElementById("city").value;
      const apiKey = "demo"; // 這裡要換成自己的 API Key
      const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric&lang=zh_tw`;

      fetch(url)
        .then(res => res.json())
        .then(data => {
          if (data.cod === 200) {
            result.innerHTML = `
              <h2>${data.name} 的天氣</h2>
              <p>溫度:${data.main.temp} °C</p>
              <p>天氣狀況:${data.weather[0].description}</p>
              <p>濕度:${data.main.humidity}%</p>
            `;
          } else {
            result.innerHTML = `<p>找不到這個城市,請再試一次。</p>`;
          }
        })
        .catch(err => {
          console.error("錯誤:", err);
          result.innerHTML = `<p>查詢失敗,請稍後再試。</p>`;
        });
    });
  </script>
</body>
</html>

小練習
美化畫面(加上背景顏色、字體)。
顯示天氣圖示(用 data.weather[0].icon)。
加上「Enter」鍵觸發查詢(不只按按鈕)。

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <title>Day22 天氣查詢</title>
  <style>
    body {
      font-family: "Segoe UI", Arial, sans-serif;
      background: linear-gradient(to right, #83a4d4, #b6fbff);
      text-align: center;
      padding: 50px;
      color: #333;
    }
    h1 {
      margin-bottom: 20px;
    }
    input {
      padding: 8px;
      font-size: 16px;
      border-radius: 5px;
      border: 1px solid #ccc;
    }
    button {
      padding: 8px 15px;
      font-size: 16px;
      margin-left: 8px;
      border: none;
      border-radius: 5px;
      background-color: #4CAF50;
      color: white;
      cursor: pointer;
    }
    button:hover {
      background-color: #45a049;
    }
    #result {
      margin-top: 30px;
      font-size: 18px;
    }
    #result img {
      margin-top: 10px;
    }
  </style>
</head>
<body>
  <h1>天氣查詢系統</h1>
  <input type="text" id="city" placeholder="輸入城市名稱,如 Taipei">
  <button id="btn">查詢</button>

  <div id="result"></div>

  <script>
    const btn = document.getElementById("btn");
    const input = document.getElementById("city");
    const result = document.getElementById("result");

    function searchWeather() {
      const city = input.value.trim();
      if (!city) {
        result.innerHTML = "<p>請輸入城市名稱。</p>";
        return;
      }

      const apiKey = "demo"; // 換成自己的 API Key
      const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric&lang=zh_tw`;

      fetch(url)
        .then(res => res.json())
        .then(data => {
          if (data.cod === 200) {
            const iconUrl = `https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png`;
            result.innerHTML = `
              <h2>${data.name} 的天氣</h2>
              <p>溫度:${data.main.temp} °C</p>
              <p>天氣狀況:${data.weather[0].description}</p>
              <p>濕度:${data.main.humidity}%</p>
              <img src="${iconUrl}" alt="天氣圖示">
            `;
          } else {
            result.innerHTML = `<p>找不到這個城市,請再試一次。</p>`;
          }
        })
        .catch(err => {
          console.error("錯誤:", err);
          result.innerHTML = `<p>查詢失敗,請稍後再試。</p>`;
        });
    }

    // 按按鈕觸發
    btn.addEventListener("click", searchWeather);

    // 按 Enter 觸發
    input.addEventListener("keypress", (e) => {
      if (e.key === "Enter") {
        searchWeather();
      }
    });
  </script>
</body>
</html>

<input>:輸入框,讓使用者輸入要查詢的城市。
id="city":給輸入框一個 ID,方便用 JavaScript 取值。
<button>:查詢按鈕。
<div id="result">:結果顯示區域,之後用 JS 把 API 回傳的天氣資訊放進去。
getElementById:選取 HTML 裡對應 ID 的元素。
input.value:取得輸入框的值。
.trim():去掉前後多餘空白,避免輸入錯誤。
if (!city):如果使用者沒有輸入城市,就顯示提示訊息並結束函式。
apiKey:你的 API Key。
q=${city}:把使用者輸入的城市帶入 API 查詢。
units=metric:設定溫度單位為攝氏。
lang=zh_tw:回傳中文天氣描述。
fetch(url):發送請求到 API。
.then(res => res.json()):把回傳結果轉換成 JSON。
.then(data => {...}):拿到 JSON 資料後進一步處理。
if (data.cod === 200):200 代表查詢成功,否則就顯示錯誤訊息。
.catch(...):處理請求失敗的情況。
data.name:城市名稱。
data.main.temp:溫度。
data.weather[0].description:天氣描述(例如「晴朗」)。
data.main.humidity:濕度。
data.weather[0].icon:天氣圖示代號,組成圖片網址顯示。
btn.addEventListener("click", searchWeather):按下按鈕時執行查詢。
input.addEventListener("keypress", ...):偵測鍵盤輸入事件。
if (e.key === "Enter"):當按下 Enter 時,也執行查詢。
這支程式的流程是 → 使用者輸入城市 → 送出請求 → API 回傳 JSON → 顯示在網頁。


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言